package com.iqiyi.pps.epg.core.dao.record;

import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.record.TRecordColSimple;
import com.iqiyi.pps.epg.api.model.web.record.TRecordColSimplePage;
import com.iqiyi.pps.epg.core.dao.base.BaseDao;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.model.record.RecordCol;
import com.iqiyi.pps.epg.core.utils.TransUtil;
import org.hibernate.Transaction;
import org.hibernate.classic.Session;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by karkarrotxu on 2018/4/11.
 */
@Component
public class RecordColDao extends BaseDao<RecordCol> {

    private List<TRecordColSimple> transToTRecordColSimpleList(List<RecordCol> dataList) {
        List<TRecordColSimple> resultList = new ArrayList<>();
        TRecordColSimple tPlan = null;
        for (RecordCol tempData : dataList) {
            tPlan = transToTRecordColSimple(tempData);
            resultList.add(tPlan);
        }
        return resultList;
    }

    public TRecordColSimple transToTRecordColSimple(RecordCol tempData) {
        TRecordColSimple _tEntity = new TRecordColSimple();
        if (tempData == null) {
            return _tEntity;
        }
        _tEntity.setId(tempData.getId());
        _tEntity.setColName(tempData.getColName());
        _tEntity.setChannelId(tempData.getChannelId());
        return _tEntity;
    }

    public TRecordColSimplePage findColSimplePage(TPage page, TFilter filter) {
        List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
        Page<RecordCol> dbPage = TransUtil.buildPage(page);
        Page<RecordCol> pageData = findPage(dbPage, filterList);
        List<RecordCol> dataList = pageData.getResult();
        TRecordColSimplePage dataPage = new TRecordColSimplePage();
        page.setTotalCount(pageData.getTotalCount());
        dataPage.setTPage(page);
        List<TRecordColSimple> tList = transToTRecordColSimpleList(dataList);
        dataPage.setResult(tList);
        return dataPage ;
    }

    public void batchUpdate(List<RecordCol> list){
        Session session = getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        try {
            for (RecordCol temp : list) {
                session.update(temp);
            }
            transaction.commit();
        } catch (Exception e) {
            logger.error(e.getMessage());
            transaction.rollback();
        } finally {
            session.close();
        }
    }
}
